package linearlist;

import java.util.Iterator;

/**
 * @Author Zhouchb
 * @Create 2021-10-2021/10/28 :11:04
 * @Description
 */
class QueueTest{
    public static void main(String[] args) {
        Queue<String> queue = new Queue<>();
        queue.enqueue("a");
        queue.enqueue("b");
        queue.enqueue("c");
        queue.enqueue("d");
        for (String s : queue) {
            System.out.println(s);
        }
        System.out.println(queue.dequeue());
        System.out.println(queue.size());
    }
}
public class Queue <T> implements Iterable<T>{
    //记录首节点
    private Node head;
    //当前队列个数
    private int N;
    //记录最后一个节点
    private Node last;

    public Queue(){
        this.head = new Node(null,null);
        this.N = 0;
        this.last = null;
    }



    private class Node{
        public T item;
        public Node next;
        public Node(T item, Node next){
            this.item = item;
            this.next = next;
        }
    }
    //判断队列是否为空，是返回true
    public boolean isEmpty(){
        return N ==0;
    }
    //获取队列中元素的个数
    public int size(){
        return N;
    }
    //从队列中拿出一个元素
    public T dequeue(){
        if (head.next==null){
            return null;
        }
        Node firstNode = head.next;
        head.next = firstNode.next;
        N--;
        if (isEmpty()){
            last=null;
        }
        return firstNode.item;
    }
    //往队列中插入一个元素
    public void enqueue(T t){
       if (last==null){
           head.next = new Node(t,null);
           last = head.next;
       }else {
           Node oldLast = last;
           last = new Node(t,null);
           oldLast.next = last;
       }
       N++;
    }

    @Override
    public Iterator<T> iterator() {
        return new getIterator();
    }
    class getIterator implements Iterator{
        public Node n;
        public getIterator(){
            n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}
